using System;
using NetMigration.DbProviders;
using NetMigration.Exceptions;
using NetMigration.SqlAssemblers;

namespace NetMigration.DAOs
{
    public class SQLServerVersionDAO : IVersionDAO
    {
        private const string VERSION_TABLE = "version_info";
        private readonly IDbProvider provider;
        private readonly ISqlAssembler sqlAssembler;

        public SQLServerVersionDAO(IDbProvider provider, ISqlAssembler sqlAssembler)
        {
            this.provider = provider;
            this.sqlAssembler = sqlAssembler;
        }

        public void CreateVersion()
        {
            string sqlText = sqlAssembler.GetSqlToCreateTable(VERSION_TABLE);
            string insertText = sqlAssembler.GetSqlToInsertValue(VERSION_TABLE, -1);
            provider.ExecuteCommand(sqlText + insertText);
        }

        public bool IsVersionExist()
        {
            string sqlText = sqlAssembler.GetSqlToCheckTableIsExist(VERSION_TABLE);
            object result = provider.ExecuteScala(sqlText);
            return result != DBNull.Value;
        }

        public void UpdateVersion(int version)
        {
            string sqlText = sqlAssembler.GetSqlToUpdateTable(VERSION_TABLE, "version", version);
            provider.ExecuteCommand(sqlText);
        }

        public int GetCurrentVersion()
        {
            try
            {
                string sqlText = sqlAssembler.GetSqlToSelect(VERSION_TABLE);
                return (int) provider.ExecuteScala(sqlText);
            }
            catch (DbProviderException)
            {
                return int.MinValue;
            }
        }
    }
}